<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<title>Geometry Engine: Overlay</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
<style>
html, body, #map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
#results{
  bottom: 50px;
  right: 20px;
  width: 275px;
}
#title{
  text-align: center;
}
#myChart{
  padding-left: 10px;
}    
.mainStyle{
  position: absolute;
  z-index: 99;
  background-color: black;
  color: cornsilk;
  border-radius: 8px;
  padding: 15px;
  opacity: 0.8;
}
</style>

<script src="http://js.arcgis.com/3.14/"></script>
<script>
var map, landLyr, utahLyr, pieChart, buffGeom;
require(["esri/map",
         "./Chart-js/Chart.js",
         "esri/graphic",
         "esri/graphicsUtils",
         "esri/geometry/Extent",
         "esri/geometry/geometryEngine",
         "esri/SpatialReference",
         "esri/symbols/SimpleFillSymbol",
         "esri/symbols/SimpleLineSymbol",
         "esri/Color",
         "esri/layers/FeatureLayer",
         "dojo/on",
         "dojo/_base/array",
         "dojo/dom",
         "dojo/domReady!"
], function(Map, Chart, Graphic, graphicsUtils, Extent, geometryEngine, SpatialReference, SimpleFillSymbol, SimpleLineSymbol, Color, FeatureLayer, on, array, dom) {
 
  var LandType = function(){
    return {
      geoms: [],
      geom: null,
      area: null,
      type: null,
      sym: null,
      color: null,
      highlight: null,
      label: null
    };
  };

  var intersectingLands = [];

  //Set up map, layers, and properties    
  var initExtent = new Extent(-12525064, 4509990, -12329386, 4621283, new SpatialReference({wkid:3857}));
  map = new Map("map", {
    basemap: "hybrid",
    extent: initExtent
  });
  on(map, "load", function(){
    map.disableMapNavigation();   
  });
 
  var landUrl = "http://tlamap.trustlands.utah.gov/arcgis/rest/services/UT_SITLA_LandOwnership/MapServer/0";
  var statesUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3";
  landLyr = new FeatureLayer(landUrl, {
    opacity: 0,
  });
  utahLyr = new FeatureLayer(statesUrl, {
    definitionExpression: "STATE_NAME = 'Utah'",
    opacity: 0
  });
  map.addLayers([utahLyr, landLyr]);
    
  //Layer symbology    
  var buffSym = new SimpleFillSymbol(SimpleFillSymbol.STYLE_NULL, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255, 1]), 3), null);
  var buffSymFade = new SimpleFillSymbol(SimpleFillSymbol.STYLE_NULL, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255, 0.4]), 10), null);
  var privateSym = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 0, 0]), 0.5), new Color([138, 138, 138, 0.7]));
  var publicSym = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 0, 0]), 0.5), new Color([161, 255, 156, 0.7]));
    
    
  //map event handlers  
  on(map, "click", createBuffer);
//  on(map, "mouse-drag", createBuffer);
  
  function createBuffer(evt){
    if(buffOpt.checked){
      intersectingLands = [];
      map.graphics.clear();
      var centerPt = evt.mapPoint;
      //Get buffer of map click point
      buffGeom = geometryEngine.geodesicBuffer(centerPt, 10, "miles");   
        
      //check if buffer is completely within Utah
      var within = geometryEngine.within(buffGeom, utahLyr.graphics[0].geometry);
      //check if buffer overlaps Utah    
      var overlaps = geometryEngine.overlaps(buffGeom, utahLyr.graphics[0].geometry);
        
      if(!within && overlaps){
         //If buffer overlaps Utah, then only get the portion within Utah  
         buffGeom = geometryEngine.intersect(buffGeom, utahLyr.graphics[0].geometry);
      }
      if(!within && !overlaps){
        //If buffer is completely outside Utah, then warn the user
        console.log("outside of utah!");          
        return;
      } 
      map.graphics.add(new Graphic(buffGeom, buffSymFade));

      var landCategories = getLand(buffGeom);
//      var publicLand = getPublicLand(buffGeom, privateLand.geom);
      generateChart(landCategories);  
    }
    else{
      return;
    }
  }
    
  function getLand(geom){
    var privateLandGraphics = landLyr.graphics;
//    var keep = [];
//    var privateLandGeoms = graphicsUtils.getGeometries(privateLandGraphics);
    //Only work with private land that intersects the buffer (essentially a select by location)  
    array.forEach(privateLandGraphics, function(item, i){
      if(geometryEngine.intersects(item.geometry, geom)){
        if(intersectingLands.length === 0){  
          var parcel = new LandType();
          parcel.geoms.push(item.geometry);
          parcel.sym = classify(item);
          parcel.type = item.attributes.STATE_LGD;
          intersectingLands.push(parcel);
            console.log("intersecting item 1: ", intersectingLands);
        }
        else{
          array.forEach(intersectingLands, function(land, j){
            if(item.attributes.STATE_LGD === land.type){
              land.geoms.push(item.geometry);
                console.log("intersecting item duplicate no. : ", j, " ", intersectingLands);
            }
            else{
              var parcel = new LandType();
              parcel.geoms.push(item.geometry);
              parcel.sym = classify(item);
              parcel.type = item.attributes.STATE_LGD;
              intersectingLands.push(parcel);
                console.log("intersecting type: #", j," ", intersectingLands);
            }
          });
        }
          
            
      }
    });
      
    array.forEach(intersectingLands, function(item, i){
      if(item.geoms.length > 1){
        var union = geometryEngine.union(item.geoms); 
        item.geom = geometryEngine.intersect(geom, union);
      }
      item.geom = geometryEngine.intersect(geom, item.geoms[0]);
      item.area = calcArea(item.geom);
      item.label = item.type + " (sq miles)";
      item.value = item.area;
      item.color = item.sym.color.toHex();
      item.highlight = setHighlight(item.sym.color);
    });
      
    console.log("intersecting lands: ", intersectingLands);
      
    return intersectingLands;
  }
    
  function setHighlight(color){
    color.r += 10;
    color.b += 10;
    color.g += 10;
      
    if(color.r > 255)
      color.r = 255;
    if(color.g > 255)
      color.g = 255;
    if(color.b > 255)
      color.b = 255;
      
    return color.toHex();
  }
    
  function classify(graphic){
    var feature, symJson, symbol;
    var type = graphic.attributes.STATE_LGD;
      if(type === "Bureau of Land Management"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [254, 230, 121, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };
      }
      if(type === "Bureau of Reclamation"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [255, 255, 179, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "Bankhead-Jones Land Use Lands"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [252, 205, 207, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "National Recreation Area"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [205, 137, 102, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "National Parks, Monuments & Historic Sites"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [202, 166, 222, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "National Forest"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [137, 205, 102, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "National Wilderness Area"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [38, 115, 0, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "National Wildlife Refuge"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [127, 204, 167, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "Other Federal"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [230, 204, 179, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "Military Reservations and Corps of Engineers"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [251, 180, 206, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "Private"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [0, 0, 0, 0],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [0, 0, 0, 0], 
                Width: 0.5
             }
         };  
      }
      if(type === "State Trust Lands"){
         symJson = {
           Style: "esriSFSSolid", 
           Color: [115, 178, 255, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         }; 
      }
      if(type === "State Sovereign Land"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [173, 201, 222, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "State Parks and Recreation"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [136, 147, 186, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "State Wildlife Reserve/Management Area"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [194, 184, 143, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "Other State"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [190, 255, 232, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      if(type === "Tribal Lands"){
        symJson = {
           Style: "esriSFSSolid", 
           Color: [253, 180, 108, 255],
           Outline:
             {
                Style: "esriSLSSolid", 
                Color: [254, 230, 121, 255], 
                Width: 0.5
             }
         };  
      }
      
      console.log("each symbol: ", new SimpleFillSymbol(symJson));
      
      return new SimpleFillSymbol(symJson);
  }    

  function calcArea(geom){
    return (Math.round(geometryEngine.geodesicArea(geom, "square-miles")*100) / 100);
  }
    
  function generateChart(objs){
    array.forEach(objs, function(item, i){
      map.graphics.add(new Graphic(item.geom, item.sym));
    });  
    map.graphics.add(new Graphic(buffGeom, buffSym));
    if(!pieChart){
      var data = objs;
      
      var opts = {
        segmentShowStroke : true,
        segmentStrokeColor : "#fff",
        segmentStrokeWidth : 2,
        percentageInnerCutout : 0,
        animationSteps : 100,
        animationEasing : "easeOutBounce",
        animateRotate : true,
        animateScale : false 
      };
    
      var ctx = document.getElementById("myChart").getContext("2d");
      pieChart = new Chart(ctx).Pie(data, opts);  
    }
    else{
      //update private land data
//      pieChart.segments[0].value = pvtData.area;
//      //update public land data
//      pieChart.segments[1].value = pubData.area;
//      pieChart.update();
    }
  }
    
  var buffOpt = dom.byId("buffOpt");
  var navOpt = dom.byId("navOpt");    
    
  on(buffOpt, "click", function(evt){
    if(buffOpt.checked){
      map.disableMapNavigation();
    }
  });
    
  on(navOpt, "click", function(evt){
    if(navOpt.checked){
      map.enableMapNavigation();
    }
  });    
    
});
</script>
</head>

<body>
  <div id="map">
    <div class="mainStyle" id="results"><h2 id="title">Utah Land Ownership</h2>
    <canvas id="myChart" width="250" height="250"></canvas><br><br>
    Click or drag on the map to view public and private land within 10 miles of map click.
    Hover over the pie chart to view the area of each ownership type within the 10-mile buffer. 
    <br><br><input type="radio" name="operation" id="buffOpt" checked>View Land Ownership
    <br><br><input type="radio" name="operation" id="navOpt">Navigate Map 
  </div>
</div>
</body>
</html>